package cn.wlinker.video.monitor.config;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.system.OsInfo;
import cn.hutool.system.SystemUtil;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;

/**
 * 静态文件访问映射
 */
@Configuration
public class StaticFileConfig implements WebMvcConfigurer {

    @Resource
    private Environment environment;

    private static String BASE_FILE_DIR;

    public static String serverPort;

    public static String contextPath;

    public static String getBaseFileDir() {
        if(StrUtil.isEmpty(BASE_FILE_DIR)){
            Environment environment = SpringUtil.getBean(Environment.class);
            OsInfo osInfo = SystemUtil.getOsInfo();
            if (osInfo.isWindows()) {
                BASE_FILE_DIR = environment.getProperty("filePath.wins");
            }
            if (osInfo.isLinux()) {
                BASE_FILE_DIR = environment.getProperty("filePath.linux");
            }
        }
        return BASE_FILE_DIR;
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //访问 /img/**会被解析为/static/img/**
        //registry.addResourceHandler("/img/**").addResourceLocations("classpath:/static/img/");
        String baseFileDir = getBaseFileDir();
        if (StrUtil.isNotBlank(baseFileDir)) {
            registry.addResourceHandler("/file/**").addResourceLocations("file:" + baseFileDir);
        }
        serverPort = environment.getProperty("server.port");
        contextPath = environment.getProperty("server.servlet.context-path");
        if (StrUtil.isBlank(contextPath)) {
            contextPath = "";
        }
    }


}
